<template>
  <Dialog
    v-model="show"
    @confirm="handleSubmit"
    @close="close"
    :title="
      props.operationType == 'edit'
        ? $t('categoryManagement.editCategory')
        : props.operationType == 'addchild'
        ? $t('categoryManagement.addSubCategoryTitle')
        : $t('categoryManagement.addCategoryTitle')
    "
    width="600px"
    :confirmLoading="loading"
  >
    <LangTabs v-model="lang" />
    <el-form :model="formData" label-width="120px" ref="formRef" :rules="rules">
      <el-form-item
        :label="$t('categoryManagement.categoryName')"
        :prop="'name' + lang"
        v-for="item in langs"
        :key="item"
        v-show="lang === item"
      >
        <el-input v-model="formData['name' + item]" :placeholder="$t('categoryManagement.pleaseEnter')" />
      </el-form-item>
      <el-form-item
        :label="$t('categoryManagement.categoryImage')"
        prop="iconUrl"
      >
        <UploadFile v-model="formData.iconUrl" :limit="1" />
      </el-form-item>
      <el-form-item :label="$t('categoryManagement.sort')" prop="sort">
        <el-input-number v-model="formData.sort" :min="0" :precision="0" />
      </el-form-item>
    </el-form>
  </Dialog>
</template>
<script setup>
import { ref, watch, reactive } from "vue";
import Dialog from "@/components/dialog.vue";
import Api from "@/config/api/api";
import { ElMessage } from "element-plus";
import LangTabs from "@/components/langTabs.vue";
import i18n from "@/i18n";
import { useI18n } from "vue-i18n";
import UploadFile from "@/components/UploadFile.vue";

const { locale, t } = useI18n();
const langs = reactive(Object.keys(i18n.global.messages.value));
const lang = ref(locale.value);
const show = defineModel();
const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
  operationType: {
    type: String,
    default: "add",
  },
});
const emit = defineEmits(["success"]);

const formData = ref({
  sort: 0,
});
const rules = ref({
  iconUrl: [{ required: true, message: t('categoryManagement.pleaseUploadImage'), trigger: "blur" }],
  sort: [{ required: true, message: t('categoryManagement.pleaseEnterSort'), trigger: "blur" }],
});
const loading = ref(false)

// 初始化表单数据和验证规则
langs.forEach((item) => {
  formData.value["name" + item] = "";
  rules.value["name" + item] = [
    { required: true, message: t('categoryManagement.pleaseEnterCategoryName'), trigger: "blur" },
  ];
});

watch(show, (val) => {
  if (val) {
    lang.value = locale.value;
    if (props.data.id) {
      formData.value = JSON.parse(JSON.stringify(props.data));
    }
    if (props.operationType == "addchild") {
      formData.value.parentId = props.data.id;
      langs.forEach((item) => {
        formData.value["name" + item] = "";
      });
    }
    if(props.data.iconUrl){
      formData.value.iconUrl = [props.data.iconUrl]
    }
  }
});

const formRef = ref();
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let res = null;
      loading.value = true
      const params = {
        parentId:
          props.operationType == "addchild"
            ? props.data.id
            : props.data.parentId || "0",
        sort: formData.value.sort,
        iconUrl: formData.value.iconUrl?.[0].url || formData.value.iconUrl?.[0] || ""
      };

      // 添加所有语言名称
      langs.forEach((item) => {
        params["name" + item] = formData.value["name" + item];
      });

      if (props.operationType == "edit") {
        params.id = props.data.id;
        res = await Api.updateBusinessCategory(params);
      } else {
        res = await Api.addBusinessCategory(params);
      }
      if (res.status === 200) {
        ElMessage.success(t('categoryManagement.operationSuccess'));
        emit("success");
        close();
      }
      loading.value = false
    }
  });
};

const close = () => {
  formData.value = {
    sort: 0
  };
  langs.forEach((item) => {
    formData.value["name" + item] = "";
  });
  show.value = false;
};
</script>
